package com.banquanhu.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Kevin on 2017/10/23.
 */

public class StreamUtils {

	public static void write(InputStream inputStream, OutputStream out) throws IOException {
		byte[] buffer = new byte[4096];
		int len;
		while ((len = inputStream.read(buffer)) > 0) {
			out.write(buffer, 0, len);
		}
	}

	public static byte[] readAsBytes(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int len;
		while ((len = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer, 0, len);
		}
		return outputStream.toByteArray();
	}

	public interface FileAction {
		public void action(File file) throws IOException;
	}

	public static void forEachFile(String path, FileAction fileAction) throws IOException {
		File pathFile = new File(path);
		forEachFile(pathFile, fileAction);
	}

	public static void forEachFile(File pathFile, FileAction fileAction) throws IOException {
		if (pathFile.isFile()) {
			fileAction.action(pathFile);
		} else if (pathFile.isDirectory()) {
			final String[] entries = pathFile.list();
			for (int i = 0; i < entries.length; i++) {
				String entry = entries[i];
				forEachFile(pathFile.toString() + File.separator + entry, fileAction);
			}
		}
	}

	public static void deleteDir(File dir) {

		File[] entries = dir.listFiles();
		if (entries != null) {
			for (int i = 0; i < entries.length; i++) {
				File entry = entries[i];
				if (entry.isDirectory())
					deleteDir(entry);
				else
					entry.delete();
			}
		}
		dir.delete();
	}
}
